package com.freesun.shop.service.imp;



import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.freesun.shop.entity.Notice;
import com.freesun.shop.mapper.NoticeMapper;
import com.freesun.shop.service.NoticeService;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.*;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zf
 * @since 2019-11-13
 */
@Service
@CacheConfig(cacheNames = "com.freesun.shop.entity.Notice")
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {

    private static Logger logger = LoggerFactory.getLogger(NoticeServiceImpl.class);
    @Override
    public IPage<Notice> findByPage(Notice notice, Page<Notice> page) {
        logger.info("公告分页查询,当前页:{},每页显示大小:{},查询的条件:{}",
                page.getCurrent(),page.getSize(), JSONUtil.toJsonStr(notice));
        IPage<Notice> iPage = this.baseMapper.selectPage(page, new LambdaQueryWrapper<Notice>()
                .select(Notice::getId,Notice::getTitle,Notice::getStatus,Notice::getIsTop)
                .like(StringUtils.hasText(notice.getTitle()), Notice::getTitle, notice.getTitle())
                .eq(notice.getStatus() != null, Notice::getStatus, notice.getStatus())
                .eq(notice.getIsTop() != null, Notice::getIsTop, notice.getIsTop()));
        return iPage;
    }

    @Override
//    @CacheEvict(key = "#id")
    @Caching(
            evict = {
                    @CacheEvict(key = "#id"),
                    @CacheEvict(key = INDEX_TOPIC_NOTICE)
            }
    )
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

    @Override
    @Cacheable(key = "#id")
    public Notice getById(Serializable id) {
        return super.getById(id);
    }

    @Override
    @Caching(
            evict = {
                    @CacheEvict(key = INDEX_TOPIC_NOTICE)
            }
    )
    public boolean save(Notice entity) {
        Assert.notNull(entity, "新增的对象不能为空");
        Assert.notNull(entity.getTitle(),"公告标题不能为空");
        entity.setUpdateTime(LocalDateTime.now());
        if(entity.getStatus()!=null&&entity.getStatus()==1){
            entity.setPublishTime(LocalDateTime.now());
        }
        return super.save(entity);
    }

    /**
     * 修改数据后缓存里面的数据会脏读
     * @param entity
     * @return
     */
    @Override
    @Caching(
            evict = {
                    @CacheEvict(key = "#entity.id"),
                    @CacheEvict(key = INDEX_TOPIC_NOTICE)
            }
    )
    public boolean updateById(Notice entity) {
        if(entity.getId()==null||entity.getTitle()==null){
            throw new RuntimeException("修改的数据不规范");
        }
        logger.info("修改公告ID为:{}",entity.getId());
        Notice notice = getById(entity.getId());
        if (null == notice) {
            throw new RuntimeException("要修改的数据不存在");
        }
        entity.setUpdateTime(LocalDateTime.now());
        if(entity.getStatus()!=null&&entity.getStatus()==1){
            entity.setPublishTime(LocalDateTime.now());
        }
        return super.updateById(entity);
    }

    /**
     * WX小程序获取置顶通知
     * @return
     */
    private static final String INDEX_TOPIC_NOTICE="'top-all-notice'";
    @Override
    @Cacheable(key = INDEX_TOPIC_NOTICE)
    public List<Notice> getTopList() {

        return this.baseMapper.selectList(new LambdaQueryWrapper<Notice>()
        .eq(Notice::getIsTop,1)
        .orderByDesc(Notice::getPublishTime));
    }
}
